<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改科室</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container mt-5">
    <h2>修改科室信息</h2>
    <form id="updateDepartmentForm">
        <input type="hidden" id="id" name="id">

        <div class="mb-3">
            <label for="name" class="form-label">科室名称</label>
            <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="mb-3">
            <label for="description" class="form-label">描述</label>
            <textarea class="form-control" id="description" name="description"></textarea>
        </div>
        <div class="mb-3">
            <label for="parentId" class="form-label">父科室ID</label>
            <input type="number" class="form-control" id="parentId" name="parentId">
        </div>
        <div class="mb-3">
            <label for="status" class="form-label">状态</label>
            <select class="form-select" id="status" name="status">
                <option value="1">启用</option>
                <option value="0">禁用</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">保存修改</button>
    </form>
</div>

<script src="/js/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        const urlParams = new URLSearchParams(window.location.search);
        const deptId = urlParams.get('id');

        if (!deptId) {
            alert("缺少科室ID");
            return;
        }

        // 获取科室信息
        $.get("/admins/getAllDepartment", function (depts) {
            const dept = depts.find(d => d.id == deptId);
            if (!dept) {
                alert("未找到该科室");
                return;
            }

            $('#id').val(dept.id);
            $('#name').val(dept.name);
            $('#description').val(dept.description);
            $('#parentId').val(dept.parentId);
            $('#status').val(dept.status);
        });

        $('#updateDepartmentForm').on('submit', function (e) {
            e.preventDefault();
            const updatedDept = {
                id: parseInt($('#id').val()),
                name: $('#name').val(),
                description: $('#description').val(),
                parentId: parseInt($('#parentId').val()),
                status: parseInt($('#status').val())
            };

            $.ajax({
                url: "/admins/updateDepartment",
                type: "PUT",
                contentType: "application/json",
                data: JSON.stringify(updatedDept),
                success: function () {
                    alert("科室信息已更新");
                    window.location.href = "/departmentList";
                },
                error: function () {
                    alert("更新失败");
                }
            });
        });
    });
</script>

</body>
</html>
